using System;
using System.Reflection;
using System.Text;
using DotNetScriptEngine;

namespace ScriptRunner
{
	class Runner
	{
		private const int NoOrErrorRetValue = -1;	

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[MTAThread]
		static void Main(string[] args)
		{	
			int retValue = NoOrErrorRetValue;

			if (args.Length == 0)
			{
				//Create file associations from .dnml files to the script engine
				CreateFileAssociation();
				Console.WriteLine("File association for .dnml files has been created");
				Console.ReadLine();
			}	
			else if (args[0].ToLower() == "remove")
			{
				//Remove file associations for .dnml files to the script engine
				RemoveFileAssociation();
				Console.WriteLine("File association for .dnml files has been removed");
				Console.ReadLine();
			}
			
			//Just to see what args are being passed in
			//foreach (string arg in args)
			//	Console.WriteLine(arg);
			if (args.Length > 0)
			{
				//string fileName = @"E:\My Documents\My Articles\Dot Net Script\Source\VB test.dnml";
				Engine engine = new Engine();
				engine.Trace += new TraceEventHandler(TraceExceptin);
				retValue = engine.RunFile(args[0]);
			}
			else
			{
				Console.WriteLine("Error:  An exception occurred while reading command arguments\r\n");
			}

			//return a value to the user
			Console.WriteLine(retValue);
		}

		internal static void CreateFileAssociation()
		{
			FileAssociation FA = new FileAssociation();
			FA.Extension = "dnml";
			FA.ContentType = "application/dotnetscript";
			FA.FullName = "DotNetScriptFiles";
			FA.ProperName = "DotNetScriptFiles";
			FA.AddCommand("open", "\"" + Assembly.GetExecutingAssembly().Location + "\" \" %1\"");			
			FA.AddCommand("edit", "notepad.exe %1");
			FA.IconPath = Assembly.GetExecutingAssembly().Location;
			FA.IconIndex = 0;
			FA.Create();
		}

		internal static void RemoveFileAssociation()
		{
			FileAssociation FA = new FileAssociation();
			FA.Extension = "dnml";
			FA.ContentType = "application/dotnetscript";
			FA.FullName = "DotNetScriptFiles";
			FA.ProperName = "DotNetScriptFiles";
			FA.AddCommand("open", Assembly.GetExecutingAssembly().Location + " %1");
			FA.AddCommand("edit", "notepad.exe %1");
			FA.IconPath = Assembly.GetExecutingAssembly().Location;
			FA.IconIndex = 0;
			FA.Remove();
		}

		private static void TraceExceptin(object sender, TraceEventArgs e)
		{
			StringBuilder log = new StringBuilder();
			Exception exception = e.Ex;

			log.Append("\r\n" + e.Trace);

			//get all the exceptions and add their error messages
			while (exception != null)
			{
				log.Append("\t" + exception.Message + "\r\n");	
				exception = exception.InnerException;
			}

			Console.WriteLine(log.ToString());
		}
	}
}
